<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="果品类型" prop="fruitType">
        <el-select v-model="queryParams.fruitType" placeholder="请选择果品类型" clearable>
          <el-option v-for="dict in base_tree_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="存储类型" prop="stockType">
        <el-select v-model="queryParams.stockType" placeholder="请选择存储类型" clearable>
          <el-option v-for="dict in base_fruit_stock_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="果品品种" prop="fruitBreed">
        <el-select v-model="queryParams.fruitBreed" placeholder="请选择果品品种" clearable>
          <el-option v-for="dict in base_fruit_breed" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="果品品种" prop="fruitBreed">
        <el-input v-model="queryParams.fruitBreed" placeholder="请输入果品品种" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="库存重量" prop="weight">
        <el-input v-model="queryParams.weight" placeholder="请输入库存重量" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库名称" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择仓库名称" clearable>
          <el-option v-for="dict in storeList" :key="dict.id" :label="dict.storeName" :value="dict.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['base:stock:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['base:stock:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['base:stock:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['base:stock:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="果品类型" align="center" prop="fruitType">
        <template #default="scope">
          <dict-tag :options="base_tree_type" :value="scope.row.fruitType" />
        </template>
      </el-table-column>
      <el-table-column label="存储类型" align="center" prop="stockType">
        <template #default="scope">
          <dict-tag :options="base_fruit_stock_type" :value="scope.row.stockType" />
        </template>
      </el-table-column>
      <el-table-column label="果品品种" align="center" prop="fruitBreed">
        <template #default="scope">
          <dict-tag :options="base_fruit_breed" :value="scope.row.fruitBreed" />
        </template>
      </el-table-column>
      <el-table-column label="库存重量" align="center" prop="weight" />
      <el-table-column label="仓库名称" align="center" prop="storeName" />

      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleOut(scope.row)"
            v-hasPermi="['base:stock:edit']">出库</el-button>
          <el-button link type="primary" icon="Edit" @click="handleInsert(scope.row)"
            v-hasPermi="['base:stock:edit']">入库</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['base:stock:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改果品库存操作对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="stockRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="果品类型" prop="fruitType">
          <el-select v-model="form.fruitType" placeholder="请选择果品类型">
            <el-option v-for="dict in base_tree_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存储类型" prop="stockType">
          <el-select v-model="form.stockType" placeholder="请选择存储类型">
            <el-option v-for="dict in base_fruit_stock_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="果品品种" prop="fruitBreed">
          <el-select v-model="form.fruitBreed" placeholder="请选择存储类型">
            <el-option v-for="dict in base_fruit_breed" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择仓库名称" clearable>
            <el-option v-for="dict in storeList" :key="dict.id" :label="dict.storeName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openMove" width="500px" append-to-body>
      <el-form ref="stockRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="重量" prop="moveWeight">
          <el-input v-model.number="form.moveWeight" placeholder="请输入库存重量" />
        </el-form-item>
        <el-form-item label="出库类型" prop="storeId" v-if="title == '出库'">
          <el-select v-model="form.fruitMoveType" placeholder="请选择出库类型" clearable>
            <el-option v-for="dict in fruit_move_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联订单" prop="storeId" v-if="title == '出库'&& form.fruitMoveType == '1' ">
          <el-select v-model="form.orderId" placeholder="请选择" clearable>
            <el-option v-for="dict in orderList" :key="dict.id" :label="dict.id"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Stock">
import { listStock, getStock, delStock, addStock, updateStock } from "@/api/base/stock";
import { listStore } from "@/api/base/store"
import { listOrder } from "@/api/base/order"
import useUserStore from "@/store/modules/user"
const userStore = useUserStore()
const { proxy } = getCurrentInstance();
const { base_fruit_stock_type, base_tree_type, base_fruit_breed, fruit_move_type } = proxy.useDict('base_fruit_stock_type', 'base_tree_type', 'base_fruit_breed', 'fruit_move_type');

const storeList = ref([])
const stockList = ref([]);
const orderList = ref([])
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openMove = ref(false)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fruitType: null,
    stockType: null,
    fruitBreed: null,
    weight: null,
    storeId: null
  },
  rules: {
    fruitType: [
      { required: true, message: "果品类型不能为空", trigger: "change" }
    ],
    stockType: [
      { required: true, message: "存储类型不能为空", trigger: "blur" }
    ],
    fruitBreed: [
      { required: true, message: "果品品种不能为空", trigger: "change" }
    ],
    storeId: [
      { required: true, message: "仓库不能为空", trigger: "blur" }
    ],
    moveWeight: [
      { required: true, message: "重量不能为空", trigger: "blur" }
    ],

  }
});

const { queryParams, form, rules } = toRefs(data);
const handleOut = async (row) => {
  reset();
  const _id = row.id || ids.value
  getStock(_id).then(response => {
    form.value = response.data;
    form.value.fruitMoveStatus = 0
    openMove.value = true;
    title.value = "出库";
    form.value.reveiveBy = userStore.userName
  });
}
const handleInsert = async (row) => {
  reset();
  const _id = row.id || ids.value
  getStock(_id).then(response => {
    form.value = response.data;
    openMove.value = true;
    title.value = "入库";
    form.value.fruitMoveStatus = 1

  });
}
/** 查询果品库存操作列表 */
function getList() {
  loading.value = true;
  listStock(queryParams.value).then(response => {
    stockList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getStoreList() {
  listStore({ type: 'fruitStore' }).then(res => {
    storeList.value = res.rows
  })
}
function getOrderList() {
  listOrder().then(res => {
    orderList.value = res.rows
  })
}
// 取消按钮
function cancel() {
  openMove.value = false
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    fruitType: null,
    stockType: null,
    fruitBreed: null,
    weight: null,
    remark: null,
    storeId: null,
    moveWeight: null,
    reveiveBy: null
  };
  proxy.resetForm("stockRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加果品库存操作";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStock(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改果品库存操作";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stockRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        if (form.value.weight == 0 && title.value == '出库') {
          proxy.$modal.msgError("库存为0，不能出库");
          return
        }

        updateStock(form.value).then(response => {
          proxy.$modal.msgSuccess(title.value + "成功");
          openMove.value = false;
          getList();
        });
      } else {
        addStock(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除果品库存操作编号为"' + _ids + '"的数据项？').then(function () {
    return delStock(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/stock/export', {
    ...queryParams.value
  }, `stock_${new Date().getTime()}.xlsx`)
}

getList();
getStoreList()
getOrderList()
</script>
